<script>
import YmSwitch from './button/YmSwitch'
import YmIconButton from './button/YmIconButton'
import YmUrlDialogButton from './button/YmUrlDialogButton'
import YmFileButton from './button/YmFileButton'
import Util from "@/util";

/**
 * 动态渲染一个按钮
 *  props: {
 *    file: YmFileButton,
 *    dialog: {string} YmUrlDialogButton,
 *    switch: {string} 绑定的字段名 生成YmSwitch
 *          : YmIconButton
 *  }
 *
 */
export default {
  name: 'YmButton',
  functional: true,
  render (h, context) {
    const { props, data, listeners } = context

    // 按钮无效
    let disabled = Util.isDisabled(props, props.row)

    let tag = getTag(props)

    const _props = {
      ...props,
      disabled
    }

    // 调节switch的绑定值
    // if (props.switch) _props.value = props.row[props.switch]

    return h(
      tag,
      {
        ...data,
        props: _props,
        on: {
          ...listeners,
          click: () => {
            if (listeners.click) listeners.click(props)
          }
        }
      },
      context.children
    )
  }
}

function getTag (props) {
  if (props.file) return YmFileButton
  if (props.dialog) return YmUrlDialogButton

  // 这个按钮响应url操作
  // props.click = true

  if (props.switch) {
    props.value = props.row[props.switch]
    return YmSwitch
  }

  return YmIconButton
}
</script>
